import {PlusOutlined} from '@ant-design/icons';
import {Button, Drawer, Form, message, Popconfirm, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable, {EditableProTable} from '@ant-design/pro-table';
import {ModalForm, ProForm, ProFormRadio, ProFormText} from '@ant-design/pro-form';
import type {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import {addAccount, removeAccount, account, updateAccount, loadAccount} from './service';
import type {AccountListItem, AccountListPagination, AccountOrg} from './data';
import {loadOrgList} from "@/pages/Enterprise/Org/service";

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: AccountListItem, edit: boolean) => {
  const hide = message.loading(edit ? '正在保存' : '正在添加');

  try {
    edit ? await updateAccount({...fields}) : await addAccount({...fields})
    hide();
    message.success(edit ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    hide();
    // message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: AccountListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeAccount(selectedRows.map((row) => row.accountId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const requestOrg = async () => {
  return loadOrgList({'status': '0'}).then(({data}) => {
    return data;
  });
};
const AccountPage: React.FC = () => {
  /** 表单窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<AccountListItem>();
  const [selectedRowsState, setSelectedRows] = useState<AccountListItem[]>([]);
  /** 国际化配置 */

  const columns: ProColumns<AccountListItem>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '手机号',
      tip: '登录账号',
      dataIndex: 'mobile',
    },
    {
      title: '邮箱',
      search: false,
      dataIndex: 'email',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      search: false,
      hideInForm: false,
      valueEnum: {
        0: {
          text: '男',
        },
        1: {
          text: '女',
        },
        2: {
          text: '未知',
        },
      },
    },
    {
      title: '管理部门',
      dataIndex: 'orgList',
      render: (_, record) => (
        <>
          {record.orgList?.map((name, index) => (
            <Tag key={name + index + record.accountId}>
              {name}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '登录IP',
      search: false,
      hideInTable: true,
      dataIndex: 'loginIp',
    },
    {
      title: '登录时间',
      search: false,
      hideInTable: true,
      dataIndex: 'loginDate',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: false,
      valueEnum: {
        0: {
          text: '启用',
          status: 'Success',
        },
        1: {
          text: '禁用',
          status: 'Error',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      defaultSortOrder: 'descend',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            record.flag = Date.now();
            setCurrentRow(record);
          }}
        >
          配置
        </a>,
        <Popconfirm
          key="delete"
          okButtonProps={{danger: true}}
          title={`确认删除管理账号：${record.name}?`}
          onConfirm={async () => {
            setCurrentRow(record);
            await handleRemove([record])
            actionRef.current?.reloadAndRest?.();
          }}
          okText="删除"
          cancelText="取消"
        >
          <a href="#"> 删除 </a>
        </Popconfirm>

      ],
    },
  ];

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [editForm] = Form.useForm()

  const authColumns: ProColumns<AccountOrg>[] = [
    {
      title: '部门',
      key: 'orgId',
      dataIndex: 'orgId',
      valueType: 'treeSelect',
      request: requestOrg,

      fieldProps: {
        dropdownMatchSelectWidth: false,
        placeholder: "请选择部门",
        treeLine: true,
        treeDefaultExpandAll: true,
        fieldNames: {label: 'label', value: 'id', children: 'children'},
      },

      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项',
          },
        ],
      },
    },
    {
      title: '是否含下级',
      key: 'hasLeaf',
      dataIndex: 'hasLeaf',
      valueType: 'select',
      width: 130,
      request: async () => {
        return [
          {value: 0, label: "不包含"},
          {value: 1, label: "包含"}
        ];
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 50,
    },
  ];


  return (
    <PageContainer>
      <ProTable<AccountListItem, AccountListPagination>
        headerTitle="账号列表"
        actionRef={actionRef}
        rowKey="accountId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              let now = Date.now();
              setEditableRowKeys([now])
              setCurrentRow({
                accountId: 0,
                mobile: "",
                name: "",
                email: "",
                status: 0,
                sex: 0,
                accountOrgList: [{id: now, hasLeaf: 1, orgLineal: []}],
                flag: Date.now(),
                scope: "org"
              });
              handleModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={account}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >

          <Popconfirm
            key="delete"
            title={`确认删除选中的${selectedRowsState.length}个管理账号?`}
            okButtonProps={{danger: true}}
            onConfirm={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="删除"
            cancelText="取消"
          >
            <Button danger>
              批量删除
            </Button>
          </Popconfirm>
          {/*<Button type="primary">批量禁用</Button>*/}
        </FooterToolbar>
      )}
      <ModalForm<AccountListItem>
        width="600px"
        title={currentRow?.accountId || 0 > 0 ? "编辑账号" : "新建账号"}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        // @ts-ignore
        onFinish={async (value) => {
          await editForm.validateFields(); // 调用表单验证
          let orgIds = [];

          for (const item of value.accountOrgList) {
            if (orgIds.indexOf(item.orgId) >= 0) {
              message.error("请不要重复选择同一个部门");
              return false;
            }
            orgIds.push(item.orgId);
          }

          const success = await handleAdd(value, value.accountId > 0);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current?.reload();
            }
          }
        }}
        request={(params) => {
          if (params.accountId > 0) {
            return loadAccount(params).then(({data}) => {

              setEditableRowKeys(() =>
                data?.accountOrgList.map((item) => item.id),
              )
              return data;
            });
          } else {
            return new Promise<AccountListItem>((resolve, reject) => {
              resolve(params as AccountListItem)
            })
          }
        }}
        params={{...currentRow}}
      >

        <ProFormText hidden name="accountId"/>
        <ProFormText hidden name="scope"/>
        <ProFormText
          rules={[
            {required: true},
            {
              pattern: /^[1][3,4,5,6,7,8,9]\d{9}$/,
              message: '请输入正确的手机号'
            }
          ]}
          label={"手机号"}
          placeholder={"管理人员手机号码"}
          name="mobile"
        />

        <ProFormText
          rules={[{required: true}]}
          label={"名称"}
          placeholder={"管理人员名称"}
          name="name"
        />
        <ProFormText
          label={"邮箱"}
          placeholder={"管理人员邮箱"}
          name="email"
        />

        <ProFormText.Password tooltip={"密码"} label={"密码"} placeholder={"请输入账号密码"} name="password"/>

        <ProForm.Group>
          <ProFormRadio.Group
            name="sex"
            label="性别"
            options={[
              {
                label: '男',
                value: 0,
              },
              {
                label: '女',
                value: 1,
              },
              {
                label: '未知',
                value: 2,
              },
            ]}
          />
          <ProFormRadio.Group
            name="status"
            label="状态"
            options={[
              {
                label: '启用',
                value: 0,
              },
              {
                label: '禁用',
                value: 1,
              },
            ]}
          />
        </ProForm.Group>


        <ProForm.Item label={"授权部门"} name="accountOrgList" trigger="onValuesChange">
          <EditableProTable<AccountOrg>
            rowKey="id"
            toolBarRender={false}
            columns={authColumns}
            onChange={(value) => {
              console.log(value)
            }}
            controlled={true}
            recordCreatorProps={{
              creatorButtonText: '新增部门',
              newRecordType: 'dataSource',
              // @ts-ignore
              record: () => ({id: Date.now(), hasLeaf: 1, orgId: null, orgLineal: []}),
            }}
            editable={{
              type: 'multiple',
              form: editForm,
              editableKeys,
              onChange: setEditableRowKeys,
              actionRender: (row, _, dom) => {
                return [dom.delete];
              },
            }}
          />
        </ProForm.Item>
      </ModalForm>

      <ModalForm<AccountListItem>
        title="账号授权"
        visible={updateModalVisible}
        onVisibleChange={handleUpdateModalVisible}
        onFinish={async (value) => {
          // const success = await handleAdd(value as TableListItem);
          // if (success) {
          //   handleModalVisible(false);
          //   if (actionRef.current) {
          //     actionRef.current.reload();
          //   }
          // }
        }}

        request={(params) => {
          return loadAccount(params).then(({data}) => {
            return data;
          });
        }}
        params={{...currentRow}}
      >
        <ProForm.Item name="accountOrgList" trigger="onValuesChange">
          <EditableProTable<AccountOrg>
            rowKey="id"
            // @ts-ignore
            form={editForm}
            maxLength={5}
            recordCreatorProps={{
              position: 'bottom',
              record: {id: Date.now(), hasLeaf: 0, orgLineal: [], orgId: undefined},
            }}
            columns={authColumns}
            // value={dataSource}
            // onChange={setDataSource}
            editable={{
              type: 'multiple',
              editableKeys,
              onSave: async (rowKey, data, row) => {
                console.log(rowKey, data, row);
                // await waitTime(2000);
              },
              onChange: setEditableRowKeys,
            }}
          />
        </ProForm.Item>
      </ModalForm>
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<AccountListItem>
            column={1}
            bordered={true}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<AccountListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default AccountPage;
